import Vue from 'vue'
import router from '@/router'
import axios from 'axios'
import qs from 'qs'
import { Loading, Message } from 'element-ui'
axios.defaults.headers = {
  'X-Requested-With': 'XMLHttpRequest',
  'Content-Type': 'application/x-www-form-urlencoded'
}
axios.defaults.timeout = 5000
let loadinginstace: any
axios.interceptors.request.use(config => {
  loadinginstace = Loading.service({ fullscreen: true })
  return config
}, error => {
  loadinginstace.close()
  Message.error('加载超时')
  return Promise.reject(error)
})
axios.interceptors.response.use(data => {
  loadinginstace.close()
  return data
}, error => {
  loadinginstace.close()
  Message.error('加载失败')
  return Promise.reject(error)
})
Vue.prototype.$get = async (url: string, data: Object) => {
  try {
    let res = (await axios.get(url, { params: data }) as any).data
    return new Promise((resolve, reject) => {
      res.code === 0 ? resolve(res) : reject(res)
    })
  } catch (err) {
    Message.error('服务器出错')
    console.log(err)
  }
}
Vue.prototype.$post = async (url: string, data: Object) => {
  try {
    let res = (await axios.post(url, qs.stringify(data)) as any).data
    return new Promise((resolve, reject) => {
      res.code === 0 ? resolve(res) : reject(res)
    })
  } catch (err) {
    Message.error('服务器出错')
    console.log(err)
  }
}
export default axios
